package com.ppt.android.base.utils

import android.annotation.SuppressLint
import android.content.res.Resources
import android.os.Build
import android.view.Display

/**
 *
 * @author ZouJiaCai
 * @since 2023/6/15 11:06
 */
object DisplayUtils {
    /**
     * 禁用 app内视图和文字大小随系统视图和文字大小改变而改变
     */
    @JvmStatic
    fun disableDisplayDpiChange(res: Resources): Resources{
        val newConfig = res.configuration
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ //字体非默认值
            LogUtils.d(this@DisplayUtils::class.simpleName, "默认字体缩放: ${res.configuration.fontScale}")
            if (res.configuration.fontScale != 1f){
                newConfig.fontScale = 1f
            }
            newConfig.densityDpi = defaultDisplayDensity
            res.updateConfiguration(newConfig,res.displayMetrics)
        }else{ // 字体非默认值
            if (res.configuration.fontScale != 1f){
                newConfig.fontScale = 1f
                res.updateConfiguration(newConfig,res.displayMetrics)
            }
        }
        return res
    }

    private val defaultDisplayDensity: Int
        @SuppressLint("PrivateApi")
        get() = try {
            val aClass = Class.forName("android.view.WindowManagerGlobal")
            val method = aClass.getMethod("getWindowManagerService")
            method.isAccessible = true
            val iwm = method.invoke(aClass)
            val getInitialDisplayDensity = iwm.javaClass.getMethod("getInitialDisplayDensity",Int::class.javaPrimitiveType)
            getInitialDisplayDensity.isAccessible = true
            val densityDpi = getInitialDisplayDensity.invoke(iwm,Display.DEFAULT_DISPLAY)
            densityDpi as Int
        }catch (e: Exception){
            e.printStackTrace()
            -1
        }
}